package com.cocos.game;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.cocos.lib.CocosHelper;
import com.cocos.lib.JsbBridge;
import com.cocos.lib.JsbBridgeWrapper;
import com.cocos.service.SDKWrapper.SDKInterface;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class JsbSDK implements SDKInterface {
    public static JsbSDK instance;
    private static final String TAG = "JsbSDK";
    Activity activity;

    private HashMap<String, Consumer<String>> callbackDictionary = new HashMap<>();
    public static AtomicInteger sharedAtomicInteger = new AtomicInteger(0);

    @Override
    public void init(Context context) {
        this.activity = (Activity) context;
        Log.i(TAG, "init: " + TAG);
        JsbSDK.instance = this;

        if (sharedAtomicInteger.compareAndSet(0, 1)) {
            instance.callbackDictionary = new HashMap<>();
        }

        JsbBridge.ICallback cb = (_arg0, _arg1) -> {
//            Log.d(TAG, "@JsbBridge.ICallback: " + _arg0 + " " + _arg1);
            instance.dispatchMsg(_arg0, _arg1);
        };

        JsbBridge.setCallback(cb);
    }

    public static void onMsg(String msgName, Consumer<String> callback) {
        if (callback != null && msgName != null) {
            instance.callbackDictionary.put(msgName, callback);
        }
    }

    public boolean dispatchMsg(String msgName, String arg) {
        Consumer<String> callback = instance.callbackDictionary.get(msgName);
        if (callback != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                callback.accept(arg);
                return true;
            }
        } else {
//            return false;
            Log.d("JsbSDK", "No callback registered for event: " + msgName);
        }
        return false;
    }

    public static void sendMsg(String msgName, Map<String, Object> map) {
        CocosHelper.runOnGameThread(() -> {
            Gson gson = new Gson();
            String jsonStr = gson.toJson(map);
            Log.i(TAG, "sendToScript: " + jsonStr);
            JsbBridge.sendToScript(msgName, jsonStr);
        });
    }
}
